const express = require('express');
const router = express.Router();
const Chat = require('../models/Chat');
const axios = require('axios');

// 获取历史记录
router.get('/history', async (req, res) => {
  const { userId, partnerId } = req.query;
  console.log(userId, '拉取历史');
  const chats = await Chat.find({
    $or: [
      { senderId: userId, receiverId: partnerId },
      { senderId: partnerId, receiverId: userId }
    ]
  }).sort({ timestamp: 1 });

  res.json(chats);
});

// 获取未读消息数
router.get('/unread/:userId', async (req, res) => {
  try {
    const unreadCounts = await Chat.aggregate([
      {
        $match: {
          receiverId: req.params.userId,
          isRead: false
        }
      },
      {
        $group: {
          _id: '$senderId',
          count: { $sum: 1 }
        }
      }
    ]);
    res.json(unreadCounts);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 标记消息为已读
router.put('/read', async (req, res) => {
  try {
    await Chat.updateMany(
      {
        senderId: req.body.senderId,
        receiverId: req.body.receiverId,
        isRead: false
      },
      { isRead: true }
    );
    res.json({ success: true });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

const { generatePrompt } = require('../services/aiPromptService');

// AI 回复接口
router.post('/ai-reply', async (req, res) => {
  const { message, style } = req.body;

  if (!message || !style) {
    return res.status(400).json({ error: '缺少 message 或 style 参数' });
  }

  const prompt = generatePrompt(style, message);

  try {
    const aiRes = await axios.post('https://api.openai.com/v1/chat/completions', {
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: prompt }],
    }, {
      headers: {
        Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
        'Content-Type': 'application/json',
      }
    });

    const reply = aiRes.data.choices[0].message.content;
    res.json({ reply });

  } catch (err) {
    console.error('AI 回复失败:', err.message);
    res.status(500).json({ error: 'AI 回复生成失败' });
  }
});

// 获取两用户之间的最后一条消息
router.get('/last-message', async (req, res) => {
  try {
    const { userA, userB } = req.query;
    const lastMessage = await Chat.findOne({
      $or: [
        { senderId: userA, receiverId: userB },
        { senderId: userB, receiverId: userA }
      ]
    })
    .sort({ timestamp: -1 })
    .select('content timestamp');
    
    res.json(lastMessage);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

module.exports = router; // ✅ 导出的是 Router 对象